package com.atguigu.controller;

import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Date:2022/11/4
 * Author:ybc
 * Description:
 */
@Controller
@RequestMapping("/houseBroker")
public class HouseBrokerController extends BaseController {

    @DubboReference
    private HouseBrokerService houseBrokerService;
    @DubboReference
    private AdminService adminService;

    @RequestMapping("/create")
    public String create(Model model){
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList", adminList);
        return "houseBroker/create";
    }

    @RequestMapping("/save")
    public String save(HouseBroker houseBroker, Model model){
        //根据选择的经纪人的id查询用户信息
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.save(houseBroker);
        return successPage(model, "新增经纪人成功");
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model){
        HouseBroker houseBroker = houseBrokerService.getById(id);
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("houseBroker", houseBroker);
        model.addAttribute("adminList", adminList);
        return "houseBroker/edit";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable Long id, HouseBroker houseBroker, Model model){
        //根据经纪人的id查询用户信息
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setId(id);
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.update(houseBroker);
        return successPage(model, "修改经纪人成功");
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id){
        houseBrokerService.delete(id);
        return "redirect:/house/"+houseId;
    }

}
